package com.xkdx.guangguang.fragment.brand;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import android.R.integer;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.xkdx.caipiao.R;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.shareclass.BrandDetail;
import com.xkdx.guangguang.sql.BrandDataHelper;
import com.xkdx.guangguang.sql.BrandSQLiteHelper;
import com.xkdx.guangguang.wiget.MyLetterListView;
import com.xkdx.guangguang.wiget.MyLetterListView.OnTouchingLetterChangedListener;

public class AtoZFragment extends BaseFragment {
	private View view;

	private ListView listview;
	private TextView overlay;
	private MyLetterListView letterListView;
	private HashMap<String, Integer> alphaIndexer;
	private String[] sections;
	private Handler handler;
	private OverlayThread overlayThread;
	public static List<BrandDetail> brandList;
	public static ArrayList<String> webNameArr = new ArrayList<String>();
	private Button back;
	private ProgressBar pb;
	private boolean isRun = true;
	private AtoZListAdapter adapter;
	private String type = "0";
	private WindowManager windowManager;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		windowManager = (WindowManager) getActivity().getSystemService(
				Context.WINDOW_SERVICE);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.atoz, container, false);
		type = getArguments().getString("tag");
		findView();
		setOnClick();
		showLoading();
		return view;
	}

	@Override
	public void findView() {
		listview = (ListView) view.findViewById(R.id.list_view);
		letterListView = (MyLetterListView) view
				.findViewById(R.id.MyLetterListView01);
		back = (Button) view.findViewById(R.id.back_AtoZ);
		pb = (ProgressBar) view.findViewById(R.id.progressbar);

	}

	private void setValuse() {
		pb.setVisibility(View.GONE);
		adapter = new AtoZListAdapter(getActivity());
		listview.setAdapter(adapter);
		letterListView
				.setOnTouchingLetterChangedListener(new LetterListViewListener());
		handler = new Handler();
		overlayThread = new OverlayThread();
		initOverlay();
		listview.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {

				if (brandList.size() > 0) {
					overlay.setText(getAlpha(brandList
							.get(firstVisibleItem + visibleItemCount / 2)
							.getAtoZ()));
					overlay.setVisibility(View.VISIBLE);
					handler.removeCallbacks(overlayThread);
					handler.postDelayed(overlayThread, 500);

				}

			}
		});
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				FragmentTransaction ft = getFragmentManager()
						.beginTransaction();
				BrandInfoFragment brandShopFragment = new BrandInfoFragment();
				Bundle b = new Bundle();
				b.putString("brandID", String.valueOf(brandList.get(position).getBrandID()));
				brandShopFragment.setArguments(b);
				ft.replace(R.id.fragment, brandShopFragment);
				ft.addToBackStack(null);
				ft.commit();
			}
		});
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				FragmentManager fm = getFragmentManager();
				fm.popBackStack();

			}
		});
	}

	private void initOverlay() {
		// overlay = (TextView)
		// LayoutInflater.from(getActivity()).inflate(R.layout.atoz_popup_char_hint,
		// null);
		// overlay.setVisibility(View.INVISIBLE);
		//
		// WindowManager.LayoutParams lp = new
		// WindowManager.LayoutParams(LayoutParams.WRAP_CONTENT,
		// LayoutParams.WRAP_CONTENT,
		// WindowManager.LayoutParams.TYPE_APPLICATION,
		// WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
		// WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
		// PixelFormat.TRANSLUCENT);
		// WindowManager windowManager = (WindowManager)
		// getActivity().getSystemService(getActivity().WINDOW_SERVICE);
		// windowManager.addView(overlay, lp);
		LayoutInflater inflater = LayoutInflater.from(getActivity());
		overlay = (TextView) inflater.inflate(R.layout.overlay, null);
		overlay.setVisibility(View.INVISIBLE);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
						| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
				PixelFormat.TRANSLUCENT);

		windowManager.addView(overlay, lp);
	}

	private class OverlayThread implements Runnable {
		@Override
		public void run() {
			overlay.setVisibility(View.GONE);
		}
	}

	private class LetterListViewListener implements
			OnTouchingLetterChangedListener {
		// @Override
		// public void onTouchingLetterChanged(final String s, float y, float x)
		// {
		// if (alphaIndexer.get(s) != null) {
		// int position = alphaIndexer.get(s);
		//
		// listview.setSelection(position);
		// overlay.setText(s);
		// overlay.setVisibility(View.VISIBLE);
		//
		// handler.removeCallbacks(overlayThread);
		// handler.postDelayed(overlayThread, 500);
		// }
		// }
		//
		// @Override
		// public void onTouchingLetterEnd() {
		// overlay.setVisibility(View.GONE);
		// }
		@Override
		public void onTouchingLetterChanged(final String s) {
			if (alphaIndexer.get(s) != null) {
				int position = alphaIndexer.get(s);
				listview.setSelection(position);
				overlay.setText(sections[position]);
				overlay.setVisibility(View.VISIBLE);
				handler.removeCallbacks(overlayThread);
				handler.postDelayed(overlayThread, 1500);
			}
		}

	}

	private class AtoZListAdapter extends BaseAdapter {
		private LayoutInflater inflater;

		public AtoZListAdapter(Context context) {
			this.inflater = LayoutInflater.from(context);
			alphaIndexer = new HashMap<String, Integer>();
			sections = new String[brandList.size()];

			for (int i = 0; i < brandList.size(); i++) {
				String currentStr = getAlpha(brandList.get(i).getAtoZ());
				String previewStr = (i - 1) >= 0 ? getAlpha(brandList
						.get(i - 1).getAtoZ()) : " ";
				if (!previewStr.equals(currentStr)) {
					// 如果有中文，打开注释,用此行代码
					// String name = getAlpha(brandList.get(i).getAtoZ());
					String name = getAlpha(brandList.get(i).getAtoZ());
					alphaIndexer.put(name, i);
					sections[i] = name;
				}
			}

		}

		public int getCount() {
			return webNameArr.size();
		}

		public Object getItem(int position) {
			return webNameArr.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.atoz_item, null);
				holder = new ViewHolder();
				holder.nameTextView = (TextView) convertView
						.findViewById(R.id.content);
				holder.alpha = (TextView) convertView.findViewById(R.id.alpha);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.nameTextView.setText(webNameArr.get(position));
			String currentStr = getAlpha(brandList.get(position).getAtoZ());
			String previewStr =(position - 1) >= 0 ? getAlpha(brandList.get(
					position - 1).getAtoZ()) : " ";
			if (!previewStr.equals(currentStr)) {
				holder.alpha.setVisibility(View.VISIBLE);
				holder.alpha.setText(currentStr);
			} else {
				holder.alpha.setVisibility(View.GONE);
			}
			return convertView;
		}

		class ViewHolder {
			TextView nameTextView, alpha;
		}
	}

	private String getAlpha(String str) {
		
		if (str == null) {
			return "#";
		}

		if (str.trim().length() == 0) {
			return "#";
		}

		String c = str.trim().substring(0, 1).toUpperCase();

		Pattern pattern = Pattern.compile("^[A-Za-z]+$");
		if (pattern.matcher(c).matches()) {
			return c;
		} else {
			return "#";
		}
	}

	@Override
	public void onPause() {
		// WindowManager windowManager = (WindowManager)
		// getActivity().getSystemService(getActivity().WINDOW_SERVICE);
		if (overlay != null) {
			overlay.removeCallbacks(overlayThread);
			overlay.setVisibility(View.INVISIBLE);
		}
		isRun = false;
		super.onPause();
	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		isRun = false;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		isRun = true;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		isRun = false;
		WindowManager windowManager = (WindowManager) getActivity()
				.getSystemService(getActivity().WINDOW_SERVICE);
		windowManager.removeView(overlay);
	}

	@Override
	public void setOnClick() {
		// TODO Auto-generated method stub

	}

	@Override
	public void showLoading() {
		AtoZTask atoZTask = new AtoZTask();
		atoZTask.execute();

	}

	@Override
	public void showLoaded(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	class AtoZTask extends AsyncTask<String, integer, String> {

		@Override
		protected String doInBackground(String... params) {
			try {

				BrandDataHelper dataHelper = new BrandDataHelper(getActivity(),
						BrandSQLiteHelper.ATOZTABLE, false);

				brandList = dataHelper.getAtoZListByTag(type + "");
				dataHelper.Close();
				alphaIndexer = new HashMap<String, Integer>();
				webNameArr.clear();
				for (int i = 0; i < brandList.size(); i++) {
					webNameArr.add(brandList.get(i).getBrandSimpleName());
				}
			} catch (Exception e) {
				letterListView.setOnTouchingLetterChangedListener(null);
			}
			return "";
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			setValuse();
		}

	}

}
